<script setup lang="ts">
import { SettingOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import Tip from '../../components/Tip/index.vue'
import { useBrandStore } from '@/store/modules/brand'

const brandStore = useBrandStore()

const TipRef = ref()

const router = useRouter()

// import type { CheckedType } from 'ant-design-vue/es/switch'
type CheckedType = boolean | string | number

type ConfType = 'layout' | 'fixedHeader' | 'fixSiderbar' | string

const props = defineProps<{
  modelValue: Record<string, string | boolean | undefined>
}>()
const emit = defineEmits(['update:modelValue'])

let theTitle = ref<string>('')
const visible = ref<boolean>(false)
const handleShowDrawer = (e: any) => {
  getInfo()
  visibleNumber.value = e

  if (visibleNumber.value == 1) {
    theTitle.value = '全局设置'
    visible.value = !visible.value
  } else if (visibleNumber.value == 2) {
    theTitle.value = '联系信息'
    visible.value = !visible.value
  } else if (visibleNumber.value == 3) {
    // TipRef.value.showModal(true)
  }
  // console.log('visibleNumber=', visibleNumber.value)
}
const colorList = ref([
  //颜色
  {
    id: 1,
    color: '#F5222D',
  },
  {
    id: 2,
    color: '#FA541C',
  },
  {
    id: 3,
    color: '#FAAD14',
  },
  {
    id: 4,
    color: '#13C2C2',
  },
  {
    id: 5,
    color: '#52C41A',
  },
  {
    id: 6,
    color: '#1890FF',
  },
  {
    id: 7,
    color: '#2F54EB',
  },
  {
    id: 8,
    color: '#722ED1',
  },
])
const colorSelected = ref(null) //选择
const isColorFlag = ref(false) // 是否显示
const visibleNumber = ref(0)

const updateConf = (val: string | CheckedType | undefined, type: ConfType) => {
  const newVal = {
    ...toRaw(props.modelValue),
    [`${type}`]: val,
  }
  emit('update:modelValue', newVal)
}

import { apply } from '../../hooks/useTheme'
const getColor = (e: any, index: any) => {
  colorSelected.value = index
  localStorage.setItem('local_theme', e)
  apply(e)
}
const getInputColor = (e: any) => {
  localStorage.setItem('local_theme', e.target.value)
  apply(e.target.value)
}

let qq = ref<string>('')
qq.value = brandStore.SettingDrawerQQ
let wx = ref<string>('')
wx.value = brandStore.SettingDrawerWx
let phone = ref<string>('')
phone.value = brandStore.SettingDrawerPhone

const modal2Visible = ref<boolean>(false)
const labelCol = {
  style: { width: '100px', textAlign: 'center' },
}
const formRef = ref()
interface FormState {
  qq?: string
  wx?: string
  phone?: string
}
const formState = ref<FormState>({})
import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  qq: [{ required: true, message: '请输入qq', trigger: 'blur' }],
  wx: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
}

// 上传图片
const imgList = ref<Array<string>>([])
interface FileItem {
  uid: string
  name?: string
  status?: string
}
const fileList = ref<FileItem[]>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  return true
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '2')
  fetch(action, {
    headers: {
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      if (result && result.data != null) {
        imgList.value.push(result.data)
      } else {
        message.error('图片太大，上传失败了!')
        fileList.value.pop()
      }
    })
    .catch(error => {
      message.error('图片太大，上传失败了')
      onError(error)
    })
}

// 删除图片
const handleRemove = (file: any) => {
  if (file.status != 'error') {
    imgList.value = imgList.value.filter(item => item != file.response.data)
  }
}

interface FileInfo {
  file: FileItem
  fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
  fileList.value = newFileList.map((item: any) => {
    if (item.response && item.response.result == false) {
      return {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    } else {
      return item
    }
  })
}

// 预览 - 开始
import type { UploadProps } from 'ant-design-vue'
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
// 预览 - 结束

// 编辑
const submit = () => {
  console.log('imgList=', imgList.value)
  formRef.value.validate().then(async () => {
    console.log('formState=', formState.value)
    let params = {
      phone: formState.value.phone,
      qq: formState.value.qq,
      wechat: formState.value.wx,
      qrCodeUrl: imgList.value[0],
      // qrCodeUrl:
      //   'https://liangpiao-ticket-img.oss-cn-beijing.aliyuncs.com/replyAnswerImg/29118543004b4048bf31fc8ede1af18a.jpg',
    }
    try {
      let { state, message: msg } = await accountApi.editContactInformation(params)
      if (state === 200) {
        message.success('编辑成功')
        modal2Visible.value = false
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
  })
}

// 查询
import pdrkf from '../../assets/kf.jpg'
let theImg = ref<string>('')
// theImg.value = pdrkf
theImg.value = brandStore.SettingDrawerImage

let shareId = ref<string>('0') // 上级id
const getInfo = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getContactInformation()
    if (state === 200) {
      formState.value.qq = data.qq
      formState.value.wx = data.wechat
      formState.value.phone = data.phone

      fileList.value = []
      fileList.value.push({
        uid: '-5',
        name: 'image.png',
        status: 'error',
        url: data.qrCodeUrl,
      })
      shareId.value = data.shareUserId
      if (data.shareUserId == '0') {
        // 没有上级
        console.log('没有上级')
      } else {
        // 有上级
        // console.log('data=', data)
        qq.value = data.shareQq
        wx.value = data.shareWechat
        phone.value = data.sharePhone
        theImg.value = data.shareQrCodeUrl
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

let iconWrapperRef = ref()
const clearStore = () => {
  iconWrapperRef.value.classList.add('rotate-animation')
  localStorage.removeItem('token')
  sessionStorage.removeItem('user')

  window.location.reload()
  router.push({ path: '/login' })
}
</script>

<template>
  <div>
    <Tip ref="TipRef"></Tip>

    <div class="ant-pro-setting-drawer-handle0">
      <div class="yifu-btn">
        <a-popconfirm
          placement="left"
          title="清理缓存，重新登录！"
          ok-text="确认"
          @confirm="clearStore"
        >
          <div ref="iconWrapperRef" class="icon-wrapper">
            <SyncOutlined style="color: #fff; font-size: 16px" />
          </div>
        </a-popconfirm>
      </div>
    </div>

    <div class="ant-pro-setting-drawer-handle1" @click="handleShowDrawer(1)">
      <div v-if="!visible" class="yifu-btn">
        <SkinOutlined style="color: #fff; font-size: 16px" />
      </div>
      <div v-if="visible && visibleNumber == 1" class="close-btn">
        <CloseOutlined style="color: #fff; font-size: 16px" />
      </div>
    </div>

    <div
      v-if="brandStore.SettingDrawerWeChatFlag"
      class="ant-pro-setting-drawer-handle2"
      @click="handleShowDrawer(2)"
    >
      <div v-if="!visible" class="yifu-btn">
        <WechatOutlined style="color: #fff; font-size: 16px" />
      </div>
      <div v-if="visible && visibleNumber == 2" class="close-btn">
        <WechatOutlined style="color: #fff; font-size: 16px" />
      </div>
    </div>

    <div
      v-if="brandStore.xinRenShiPinFlag"
      class="ant-pro-setting-drawer-handle3"
      @click="handleShowDrawer(3)"
    >
      <div v-if="!visible" class="yifu-btn">
        <VideoCameraOutlined style="color: #fff; font-size: 16px" />
      </div>
      <div v-if="visible && visibleNumber == 3" class="close-btn">
        <VideoCameraOutlined style="color: #fff; font-size: 16px" />
      </div>
    </div>
  </div>

  <a-drawer v-model:open="visible" placement="right" :title="theTitle">
    <div style="margin-bottom: 24px" v-if="visible && visibleNumber == 1">
      <h3>导航模式</h3>
      <a-radio-group :value="modelValue.layout" @change="e => updateConf(e.target.value, 'layout')">
        <a-radio value="side">左侧菜单布局</a-radio>
        <a-radio value="top">顶部菜单布局</a-radio>
        <a-radio value="mix">混合菜单布局</a-radio>
      </a-radio-group>
      <a-divider />
      <a-row style="margin-bottom: 12px">
        <div class="color-container">
          <div class="left">
            <div
              class="color-item"
              :class="{ active: colorSelected === index }"
              :style="{ background: `${item.color}` }"
              v-for="(item, index) in colorList"
              @click="getColor(item.color, index)"
            >
              <div class="color-circle" :style="{ backgroundColor: item.color }"></div>
              <!-- <div class="color-pos"></div> -->
            </div>
          </div>
          <div class="right">
            <div
              class="right-color"
              @click="isColorFlag = true"
              style="
                background: conic-gradient(
                  from 90deg at 50% 50%,
                  rgb(255, 0, 0) -19.41deg,
                  rgb(255, 0, 0) 18.76deg,
                  rgb(255, 138, 0) 59.32deg,
                  rgb(255, 230, 0) 99.87deg,
                  rgb(20, 255, 0) 141.65deg,
                  rgb(0, 163, 255) 177.72deg,
                  rgb(5, 0, 255) 220.23deg,
                  rgb(173, 0, 255) 260.13deg,
                  rgb(255, 0, 199) 300.69deg,
                  rgb(255, 0, 0) 340.59deg,
                  rgb(255, 0, 0) 378.76deg
                );
              "
              type="color"
            >
              <input type="color" class="color-input" @input="getInputColor" v-if="isColorFlag" />
            </div>
          </div>
        </div>
      </a-row>
      <a-divider />

      <a-row style="margin-bottom: 12px">
        <a-col :span="12">固定 Header</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.fixedHeader"
            @change="checked => updateConf(checked, 'fixedHeader')"
          />
        </a-col>
      </a-row>

      <a-row style="margin-bottom: 12px">
        <a-col :span="12">固定 左侧菜单</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.fixSiderbar"
            @change="checked => updateConf(checked, 'fixSiderbar')"
          />
        </a-col>
      </a-row>

      <a-row style="margin-bottom: 12px">
        <a-col :span="12">自动分割菜单</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.splitMenus"
            @change="checked => updateConf(checked, 'splitMenus')"
          />
        </a-col>
      </a-row>

      <a-divider />
      <h3>内容区域</h3>
      <a-row style="margin-bottom: 12px">
        <a-col :span="12">顶栏</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.headerRender === undefined"
            @change="checked => updateConf(checked === true && undefined, 'headerRender')"
          />
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 12px">
        <a-col :span="12">页脚</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.footerRender === undefined"
            @change="checked => updateConf(checked, 'footerRender')"
          />
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 12px">
        <a-col :span="12">菜单</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            disabled
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.menu === undefined"
            @change="checked => updateConf(checked === true && undefined, 'menu')"
          />
        </a-col>
      </a-row>
      <a-row style="margin-bottom: 12px">
        <a-col :span="12">菜单头</a-col>
        <a-col :span="12" style="text-align: right">
          <a-switch
            checked-children="开"
            un-checked-children="关"
            :checked="modelValue.menuHeaderRender === undefined"
            @change="checked => updateConf(checked === true && undefined, 'menuHeaderRender')"
          />
        </a-col>
      </a-row>
    </div>

    <div style="height: 100%; position: relative" v-if="visible && visibleNumber == 2">
      <div class="contcat">
        <!-- <a-divider>上级信息</a-divider> -->
        <div style="margin: 0 auto">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="联系电话">{{ phone }}</a-descriptions-item>
            <a-descriptions-item label="联系QQ">{{ qq }}</a-descriptions-item>
            <a-descriptions-item label="联系微信">{{ wx }}</a-descriptions-item>
          </a-descriptions>
        </div>

        <div class="kfImg" style="margin-top: 5px">
          <img :src="theImg" alt="暂无客服微信二维码" />
        </div>

        <div style="text-align: center; margin-top: 10px" v-if="brandStore.SettingDrawerIsSetFlag">
          <a-button block @click="modal2Visible = true">设置联系信息</a-button>
        </div>
        <div style="margin-top: 10px">
          <span style="color: rgba(0, 0, 0, 0.45); font-size: 13px">
            tips: 通过您邀请码注册的用户，可看到您的联系信息
          </span>
        </div>
      </div>
    </div>
  </a-drawer>

  <a-modal v-model:open="modal2Visible" title="设置联系信息" centered @ok="submit">
    <a-form ref="formRef" :rules="rules" :model="formState" :label-col="labelCol">
      <a-form-item label="联系QQ" name="qq">
        <a-input v-model:value="formState.qq" style="width: 70%"></a-input>
      </a-form-item>
      <a-form-item label="联系微信" name="wx">
        <a-input v-model:value="formState.wx" style="width: 70%"></a-input>
      </a-form-item>
      <a-form-item label="联系电话" name="phone">
        <a-input v-model:value="formState.phone" style="width: 70%"></a-input>
      </a-form-item>
      <a-form-item name="image" label="联系方式" help="推荐使用黑白底的联系二维码，显示更佳～">
        <!-- action="http://ticket-expert-api.liangpiaovip.com/platform/wechatReply/uploadToAliOss" -->
        <!-- action="http://k8s-cluster.liangpiaovip.com:30080/ticket-expert/platform/wechatReply/uploadToAliOss" -->
        <a-upload
          :multiple="true"
          list-type="picture-card"
          action="http://crm.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
          :show-upload-list="{ showRemoveIcon: true }"
          :max-count="1"
          :beforeUpload="handleBeforeUpload"
          :customRequest="customRequest"
          @preview="handlePreview"
          @remove="handleRemove"
          @change="handleChange"
          :file-list="fileList"
        >
          <upload-outlined></upload-outlined>
          更新图片
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<style lang="less" scoped>
.rotate-animation {
  animation: rotate-3-times 3s linear forwards;
}

@keyframes rotate-3-times {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(1080deg); /* 3圈 * 360度 */
  }
}

.contcat {
  overflow-x: hidden;
  overflow-y: scroll;
  position: absolute;
  margin-bottom: 20px;
  // top: 40%;
  // transform: translateY(-50%);

  background-size: cover;
  width: 100%;
  // background: pink;
}

.kfImg {
  background-size: cover;
  width: 100%;
  height: 400px;

  // background: pink;
  img {
    // height: 40px;
    width: 100%;
  }
}

.ant-pro-setting-drawer-handle0 {
  position: fixed;
  top: 30%;
  // right: 320px;
  right: 0;
  transform: translateY(-40%);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  font-size: 16px;
  text-align: center;
  background: var(--primary-color);
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  pointer-events: auto;

  .yifu-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  .close-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  > span {
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
}

.ant-pro-setting-drawer-handle1 {
  position: fixed;
  top: 40%;
  // right: 320px;
  right: 0;
  transform: translateY(-40%);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  font-size: 16px;
  text-align: center;
  background: var(--primary-color);
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  pointer-events: auto;

  .yifu-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  .close-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  > span {
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
}

.ant-pro-setting-drawer-handle2 {
  position: fixed;
  top: 50%;
  // right: 320px;
  right: 0;
  transform: translateY(-50%);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  font-size: 16px;
  text-align: center;
  background: var(--primary-color);
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  pointer-events: auto;

  .yifu-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  .close-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  > span {
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
}

.ant-pro-setting-drawer-handle3 {
  position: fixed;
  top: 60%;
  // right: 320px;
  right: 0;
  transform: translateY(-50%);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  font-size: 16px;
  text-align: center;
  background: var(--primary-color);
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  pointer-events: auto;

  .yifu-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  .close-btn {
    background-color: #1890ff;
    padding: 15px;
    border-radius: 3px;
  }

  > span {
    color: rgb(255, 255, 255);
    font-size: 20px;
  }
}

.color-container {
  display: flex;
  align-items: center;

  .left {
    display: flex;
    align-items: center;

    .color-item {
      width: 22px;
      height: 22px;
      border-radius: 50%;
      cursor: pointer;
      position: relative;

      .color-circle {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        border-radius: 50%;
        /* 圆形 */
        opacity: 0;
        /* 初始时不可见 */
        transition: transform 0.3s, opacity 0.3s;
        /* 动画效果 */
        pointer-events: none;
        /* 防止点击穿透 */
      }
    }

    .color-item:nth-child(n + 2) {
      margin-left: 8px;
    }

    .color-item.active .color-circle {
      transform: scale(1.4);
      /* 放大效果 */
      opacity: 0.5;
      /* 显示并设置透明度 */
    }

    .active {
      background-color: #fff;
      width: 22px;
      height: 22px;
      border-radius: 50%;
    }
  }

  .right {
    margin-left: 10px;

    .right-color {
      border-radius: 50% !important;
      width: 22px !important;
      height: 22px !important;
      position: relative;

      .color-input {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        opacity: 0;
        cursor: pointer;
        // z-index: -3;
      }
    }
  }
}
</style>
